#pragma once
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/resource.h>

#include "../Comm/util.hpp"
#include "../Comm/log.hpp"

namespace ns_runner
{
    using namespace ns_util;
    using namespace ns_log;

    class Runner
    {
    public:
        Runner()
        {
        }
        ~Runner()
        {
        }

    public:
        static void SetProcLimit(int _cpu_limit, int _mem_limit)
        {
            // 设置CPU时长
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            cpu_rlimit.rlim_cur = _cpu_limit;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);

            // 设置内存大小
            struct rlimit mem_rlimit;
            mem_rlimit.rlim_max = RLIM_INFINITY;
            mem_rlimit.rlim_cur = _mem_limit * 1024; // 转化成为KB
            setrlimit(RLIMIT_AS, &mem_rlimit);
        }

    public:
        static int Run(const std::string &filename, int cpu_limit, int mem_limit)
        {
            // 运行程序：1.需要知道待运行的程序是谁
            // 程序运行时，默认会打开3个文件。其中标准输入不处理（不考虑用户自行输入的测试用例）
            std::string _execute = PathUtil::Exe(filename);
            std::string _stdin = PathUtil::Stdin(filename);
            std::string _stdout = PathUtil::Stdout(filename);
            std::string _stderr = PathUtil::Stderr(filename);

            umask(0);
            int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);

            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(ERROR) << "打开标准文件失败" << "\n";
                return -1;
            }

            pid_t id = fork();
            if (id < 0)
            {
                LOG(ERROR) << "运行时创建子进程失败" << "\n";
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                return -2;
            }
            else if (id == 0)
            {
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);

                // SetProLimit(cpu_limit, mem_limit);
                execl(_execute.c_str(), _execute.c_str(), nullptr);
                exit(1);
            }
            else
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);

                int status;
                waitpid(id, &status, 0);
                LOG(INFO) << "运行完毕, info: " << (status & 0x7F) << "\n";
                return (status & 0x7F);
            }
        }
    };
}